/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.ejb.EJB;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jsonHelper.SimpleUser;
import service.Audio;
import service.AudioFacadeREST;
import service.MumuUser;
import service.MumuUserFacadeREST;
import service.Photo;
import service.PhotoCollection;
import service.PhotoCollectionFacadeREST;
import service.PhotoFacadeREST;
import service.Planet;
import service.PlanetFacadeREST;
import service.Universe;
import service.UniverseFacadeREST;
import service.Video;
import service.VideoFacadeREST;
import session.UserData;
import utilities.ReadSmtp;

/**
 *
 * @author andrew
 */
public class AdminUserServlet extends HttpServlet {
    
    @EJB
    private MumuUserFacadeREST userManager;
    
    @EJB
    private UniverseFacadeREST universeManager;
    
    @EJB
    private PlanetFacadeREST planetManager;
    
    @EJB
    private AudioFacadeREST audioManager;
    
    @EJB
    private VideoFacadeREST videoManager;
    
    @EJB
    private PhotoCollectionFacadeREST photoCollectionManager;
    
    @EJB
    private PhotoFacadeREST photoManager;
    
    private Session session;

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        Gson gson = new Gson();
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        
        HttpSession session = request.getSession();
        
        UserData userData = (UserData)session.getAttribute("userData");
        Integer idCurrentUser = userData.getIDUser();
        
        MumuUser currentUser = userManager.find(idCurrentUser);
        
        List<MumuUser> listUser = userManager.findAll();
        
        ArrayList<SimpleUser> arraySimpleUser = new ArrayList<SimpleUser>();
        
        Iterator<MumuUser> itUser = listUser.iterator();
        
        while(itUser.hasNext()){    
            MumuUser user = itUser.next();
            
            if(!user.getMail().equals(currentUser.getMail())){
                SimpleUser simpleUser = new SimpleUser();
            
                simpleUser.setIdUser(user.getIdUser());
                simpleUser.setName(user.getNameSurname());
                simpleUser.setEmail(user.getMail());
                simpleUser.setQualification(user.getQualification());

                // privilegi 
    //                0 = non validato
    //                1 = validato
    //                2 = amministratore



                if(user.getIsAdministrator()){
                    simpleUser.setPrivilege(2);
                }else if(user.getIsValidated()){
                    simpleUser.setPrivilege(1);
                }else{
                    simpleUser.setPrivilege(0);
                }

                arraySimpleUser.add(simpleUser);
                }
            
        }
        
        String StringToClientUser = gson.toJson(arraySimpleUser);
        // restituzione JSON
        out.println(StringToClientUser);
        out.close();
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
     
        String idUserString = request.getParameter("idUser");
        int idUser = Integer.parseInt(idUserString);
        String actionString = request.getParameter("action");
        
        final ReadSmtp readSmtp = new ReadSmtp(request);
        
        MumuUser user = userManager.find(idUser);
        
        if(actionString.equals("delete")){
            
            System.out.println("ok siamo in Delete");
            System.out.println("ID user: "+idUser);
            
            // cerca id universo dell'utente e per ognuno cancella i file e cartelle associate
            deleteFolderAndFile(request, user);
            
            // rimozione universo
            Collection<Universe> collUniverse = user.getUniverseCollection();
            System.out.println("Dim universe: "+collUniverse.size());
            Iterator<Universe> itUniverse = collUniverse.iterator();
            
            System.out.println("iniziamo a cancellare");
            
            while(itUniverse.hasNext()){
                Universe u = itUniverse.next();
                System.out.println(" 1 - prendo in esame universo: "+u.getIdUniverse());
                // rimozione pianeta
                Collection<Planet> collPlanet = u.getPlanetCollection();
                Iterator<Planet> itPlanet = collPlanet.iterator();
                while(itPlanet.hasNext()){
                    Planet p = itPlanet.next();
                    System.out.println(" 2 - con pianeta: "+p.getIdPlanet());
                    // rimozione audio
                    Collection<Audio> collAudio = p.getAudioCollection();
                    Iterator<Audio> itAudio = collAudio.iterator();
                    while(itAudio.hasNext()){
                        Audio audio = itAudio.next();
                        System.out.println(" 3 - ha audio: "+audio.getIdAudio());
                        audioManager.remove(audio);
                        itAudio.remove();
                    }
                    
                    // rimozione video
                    Collection<Video> collVideo = p.getVideoCollection();
                    Iterator<Video> itVideo = collVideo.iterator();
                    while(itVideo.hasNext()){
                        Video video = itVideo.next();
                        System.out.println(" 3 - ha video: "+video.getIdVideo());
                        videoManager.remove(video);
                        itVideo.remove();
                    }
                    
                    
                    // rimozione immagini
                    Collection<PhotoCollection> collPhotoColl = p.getPhotoCollectionCollection();
                    Iterator<PhotoCollection> itPhotoCollection = collPhotoColl.iterator();
                    while(itPhotoCollection.hasNext()){
                        PhotoCollection photoCollection = itPhotoCollection.next();
                        System.out.println(" 4 - PhotoCollection: "+photoCollection.getIdPhotoCollection());
                        // cancello vere photo
                        Collection<Photo> collPhoto = photoCollection.getPhotoCollection();
                        Iterator<Photo> itPhoto = collPhoto.iterator();
                        while(itPhoto.hasNext()){
                            Photo photo = itPhoto.next();
                            System.out.println(" 5 - nella photoCollection: "+photoCollection.getIdPhotoCollection()+" si ha foto: "+photo.getIdPhoto());
                            photoManager.remove(photo);
                            itPhoto.remove();
                        }
                        
                        
                        photoCollectionManager.remove(photoCollection);
                        itPhotoCollection.remove();
                    }
                    
                    
                    planetManager.remove(p);
                    itPlanet.remove();
                }
                
                universeManager.remove(u);
                itUniverse.remove();
            }
           
            
            // cancellazione utente da db
            userManager.remove(user); 
            
            // invio mail di notifica all'utente
            Properties props = new Properties();
            props.put("mail.smtp.host", readSmtp.getSmtp_address());
            props.put("mail.smtp.socketFactory.port", readSmtp.getSmtp_port());
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", readSmtp.getAuth());
            props.put("mail.smtp.port", readSmtp.getSmtp_port());

            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            // email address e password
                            return new PasswordAuthentication(readSmtp.getAuth_username(), readSmtp.getAuth_password());
                        }
                    });

            try {
                InternetAddress from = new InternetAddress( user.getMail(), "UniverseCreator" );
                
                Message message = new MimeMessage(session);
                message.setFrom(from);
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.getMail()));
                message.setSubject("UniverseCreator: esito registrazione");
                String content = "Gentile " + user.getNameSurname() + ",<br/><br/>"
                        + "Il tuo account "+ user.getMail() +" &egrave; stato rifiutato.<br/>"
                        + "<br/><br/><br/>"
                        + "<i>Staff di UniverseCreator</i>"
                        + "<br/><br/><br/>"
                        + "Non rispondere, messaggio generato in automatico da UniverseCreator.<br/>";
                message.setContent(content, "text/html");
                Transport.send(message);
            } catch (Exception e) {
                System.err.println(e.getCause());
            }
            
            
        }else if(actionString.equals("edit")){
            // modifica privilegio utente
            
            String stringForMail = "";
            
            String privilege = request.getParameter("privilege");
            
            if(privilege.equals("admin")){
                
                // setto come amministratore
                user.setIsAdministrator(true);
                user.setIsValidated(true);
                stringForMail = "Amministratore di UniverseCreator.";
                
            }else if(privilege.equals("creator")){
                // setto come creatore
                user.setIsAdministrator(false);
                user.setIsValidated(true);
                stringForMail = "Creatore di universi in UniverseCreator.";
            }
            
            userManager.edit(user);
            
            
            
            // invio mail di notifica all'utente
            Properties props = new Properties();
            props.put("mail.smtp.host", readSmtp.getSmtp_address());
            props.put("mail.smtp.socketFactory.port", readSmtp.getSmtp_port());
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", readSmtp.getAuth());
            props.put("mail.smtp.port", readSmtp.getSmtp_port());

            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            // email address e password
                            return new PasswordAuthentication(readSmtp.getAuth_username(), readSmtp.getAuth_password());
                        }
                    });

            try {
                InternetAddress from = new InternetAddress( user.getMail(), "UniverseCreator" );
                
                Message message = new MimeMessage(session);
                message.setFrom(from);
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.getMail()));
                message.setSubject("UniverseCreator: esito registrazione");
                String content = "Gentile " + user.getNameSurname() + ",<br/><br/>"
                        + "Il tuo account &egrave; stato registrato con successo con privilegi di "+stringForMail+"<br/>"
                        + "<br/>"
                        + "Per accedere all'area riservata utilizza<br/> "
                        + "username: " + user.getMail() + "<br/>"
                        + "e password da te inserita al momento della registrazione.<br/>"
                        + "<br/><br/>Ti ricordiamo che se non ricordi pi&ugrave; la password, puoi recuperarla in qualsiasi momento semplicemente cliccando sul link che trovi in homepage."
                        + "<br/><br/><br/>"
                        + "<i>Staff di UniverseCreator</i>"
                        + "<br/><br/><br/>"
                        + "Non rispondere, messaggio generato in automatico da UniverseCreator.<br/>";
                message.setContent(content, "text/html");
                Transport.send(message);
            } catch (Exception e) {
                System.err.println(e.getCause());
            }
            
        }else{
            // richiesta farlocca
            response.sendRedirect("home.jsp");
        }
        
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    
    private void deleteFolderAndFile(HttpServletRequest request, MumuUser u){
     
        // prendo tutti gli universi associati all'utente
        Collection<Universe> collUniverse = u.getUniverseCollection();
        
        // se contiene almeno un universo prendo i path dei file associati
        if(!collUniverse.isEmpty() && collUniverse != null){
            
         Iterator<Universe> itUniverse = collUniverse.iterator();
         while(itUniverse.hasNext()){
             //prendo i pianeti associati
             
             Universe universe = itUniverse.next();
             
             File CurrentDirectory = new File(request.getServletContext().getRealPath("/")+"Universes/"+universe.getIdUniverse());
             
             System.out.println("valore currentDirectory: "+request.getServletContext().getRealPath("/")+"Universes/"+universe.getIdUniverse());
             
             // assicurazione che la cartella esista
             if(!CurrentDirectory.exists()){
                System.out.println("Directory to delete in <ADMIN: delete user> does not exist.");
             
             }else{

                try{
                    // cancellazione
                    delete(CurrentDirectory);

                }catch(IOException e){}
             }
             
         }
            
        }
        
    }
    
    
    private static void delete(File file) throws IOException{
 
    	if(file.isDirectory()){
 
    		//la directory è vuota, quindi elimina
    		if(file.list().length==0){
 
    		   file.delete();
    		   System.out.println("Directory is deleted : "  + file.getAbsolutePath());
 
    		}else{
 
    		   //lista tutte le directory contenute
        	   String files[] = file.list();
 
        	   for (String temp : files) {
        	      //costruisci la struttura del file
        	      File fileDelete = new File(file, temp);
 
        	      //cancellazione ricorsiva
        	     delete(fileDelete);
        	   }
 
        	   //controlla ancora la directory, se è vuota cancellala
        	   if(file.list().length==0){
           	     file.delete();
        	     System.out.println("Directory is deleted : " + file.getAbsolutePath());
        	   }
    		}
 
    	}else{
    		//se è un file allora cancellalo
    		file.delete();
    		System.out.println("File is deleted : " + file.getAbsolutePath());
    	}
    }
}
